

import org.json.JSONArray;
import org.json.JSONObject;

import javax.swing.ButtonGroup;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.SwingConstants;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableModel;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Vector;
import java.awt.event.ActionListener;
import java.awt.Font;
import java.awt.event.ActionEvent;
import javax.swing.JTextPane;
import java.awt.Color;



public class StudentInfo extends JPanel {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private JTable table;
	private JTextField TF_name;
	private JTextField TF_number;
	private JComboBox<String> CB_room;
	private JTextField TF_note;
	private Vector<Object[]> all_data;
	private final ButtonGroup buttonGroup = new ButtonGroup();
	private JTextPane TP_roommate;
	private JTextField TF_search;
	private JScrollPane scrollPane;
	private DefaultTableModel model;
	
	private JPanel P_student_info;
	public JComboBox<String> comboBox;
	private JButton B_add;
	private JButton B_fix;
	private JButton B_del;
	private JLabel L_name;
	private JLabel L_sex;
	private JRadioButton student_sex_boy;
	private JRadioButton student_sex_girl;
	private JLabel L_number;
	private JLabel L_room;
	private JLabel L_note;
	private JButton B_enter;
	private JButton B_cancel;
	private JLabel L_roommate;
	private JButton B_search;
	private JScrollPane scrollPane_1;
	private String S_lastPerform;
	//private String fix_student_number; //修改的学生数据的原学号
	/**
	 * Create the panel.
	 */
	
	private void updateComboBox(){
		String sendMsg = "{\"method\":\"show_room\",\"room_sex\":\""+(student_sex_boy.isSelected()?"boy":"girl")+"\",\"room_status\":\"avilable\"}";
		try{
			JSONObject obj = new JSONObject(new SocketOp().request(sendMsg));
			if(obj.has("result")){
				JSONArray arr = new JSONArray(obj.get("result").toString());
				CB_room.removeAllItems();
				CB_room.addItem("");
				for(int i=0;i<arr.length();i++){
					CB_room.addItem(arr.getString(i));
					if(arr.getString(i).equals(all_data.get(table.getSelectedRow()<0?0:table.getSelectedRow())[3].toString())){
						CB_room.setSelectedIndex(i+1);
					}
				}
			}
		}catch(Exception e){
			
		}
	}
	
	private void clearData(){
		TF_number.setText("");
		TF_name.setText("");
		TF_note.setText("");
		student_sex_boy.setSelected(true);
		student_sex_girl.setSelected(false);
		TP_roommate.setVisible(false);
		L_roommate.setVisible(false);
		TP_roommate.setBorder(null);
	}
	private boolean checkTextLengh(String text,int len,String Name){
		if(text.length()>len)
		{
			JOptionPane.showMessageDialog(null,Name+"不得超过"+len+"个字符",Name+"错误",JOptionPane.ERROR_MESSAGE);
			return false;
		}
		return true;
	}
	
	private boolean checkID(String id){
		for(int i=0;i<id.length();i++){
			if(i==0){
				if(id.charAt(i)=='0') {
					JOptionPane.showMessageDialog(null, "学号需为12位首项不为0的数字","学号错误", JOptionPane.ERROR_MESSAGE);
					return false;
				}
			}
			if(!Character.isDigit(id.charAt(i))){
				JOptionPane.showMessageDialog(null, "学号需为12位首项不为0的数字","学号错误", JOptionPane.ERROR_MESSAGE);
				return false;
			}
		}
		try{
			JSONObject obj = new JSONObject(new SocketOp().request("{\"method\":\"get_student\",\"student_number\":\""+id+"\"}"));
			if(obj.has("student_number")&&obj.getString("student_number").equals(id)){
				JOptionPane.showMessageDialog(null, "当前学号已存在","学号错误", JOptionPane.ERROR_MESSAGE);
				return false;
			}else{
				return true;
			}
		}catch(Exception e){
			return true;
		}
	}
	
	
	private String getRoommate(String student_number,String room_name){
		String recv = "";
		try{
			String sendMsg = "{\"method\":\"get_room\",\"room_name\":\""+room_name+"\"}";
			
			JSONObject obj = new JSONObject(new SocketOp().request(sendMsg));
			JSONArray arr = new JSONArray(obj.get("room_member").toString());
			for(int i=0;i<arr.length();i++){
				if(!arr.getString(i).equals(student_number)){
					String stuSendMsg = "{\"method\":\"get_student\",\"student_number\":\""+arr.getString(i)+"\"}";
					JSONObject objStu = new JSONObject(new SocketOp().request(stuSendMsg));
					recv += objStu.getString("student_number")+" "+objStu.getString("student_name")+"\n";
				}
			}
		}catch(Exception e){
		//	JOptionPane.showMessageDialog(null, e);
		}
		return recv;
	}
	public boolean updateData(String sendMsg){
		
		try{
			while(model.getRowCount()>0)
				model.removeRow(model.getRowCount()-1);
			all_data.clear();
			
			JSONObject obj = new JSONObject(new SocketOp().request(sendMsg));
			if(obj.has("result"))
			{

				JSONArray arr = new JSONArray(obj.get("result").toString());
				ArrayList<String> arrStr = new ArrayList<String>();
				for(int i=0;i<arr.length();i++){
					arrStr.add(arr.getString(i));
				}
				arrStr.sort(null);
				for(int i=0;i<arrStr.size();i++)	{
					JSONObject stuObj = new JSONObject(new SocketOp().request(new String("{\"method\":\"get_student\",\"student_number\":\""+arrStr.get(i)+"\"}")));
					all_data.addElement(new Object[]{stuObj.get("student_number").toString(),stuObj.get("student_name").toString(),stuObj.get("student_sex").toString(),stuObj.get("student_room").toString(),stuObj.get("student_note").toString()});
					model.addRow(new Object[]{stuObj.get("student_number").toString(),stuObj.get("student_name").toString(),stuObj.get("student_sex").toString(),stuObj.get("student_room").toString(),stuObj.get("student_note").toString()});
				}
			}
		}catch(Exception e1){
			
		}
		return true;
	}

	public StudentInfo() {
		setBorder(new TitledBorder(null, "information", TitledBorder.LEADING, TitledBorder.TOP, null, null));

		setLayout(null);
		scrollPane = new JScrollPane();
		
		scrollPane.setBounds(10, 52, 521, 218);
		add(scrollPane);
		table = new JTable();
		
		table.setShowGrid(false);
		table.setBounds(106, 113, 349, 292);
		table.setFont(new Font("楷体", Font.PLAIN, 15));
		table.setShowVerticalLines(false);
		scrollPane.setViewportView(table);
		String[] headers = {"学号","姓名","性别","宿舍","备注"};
		Object[][] cellData = null;
		model = new DefaultTableModel(cellData, headers) {
			/**
			 * 
			 */
			private static final long serialVersionUID = 1L;

			public boolean isCellEditable(int row, int column) {	
				return false;
			}
		};
		table.setModel(model);
		table.setRowHeight(30);  

		table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		all_data = new Vector<Object[]>();
		
		//
		//init_test_model();
		
//		table.setBorder(BorderFactory.createLineBorder(Color.BLACK));
		table.setBorder(null);
		table.setBackground(getBackground());
		P_student_info = new JPanel();
		P_student_info.setBorder(new TitledBorder(null, "详细信息", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		P_student_info.setBounds(10, 280, 521, 202);
		add(P_student_info);
		P_student_info.setLayout(null);
		
		B_add = new JButton("增加");
		
		B_add.setBounds(103, 169, 83, 23);
		P_student_info.add(B_add);
		
		B_fix = new JButton("修改");
		B_fix.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
			}
		});
		B_fix.setBounds(10, 169, 83, 23);
		P_student_info.add(B_fix);
		
		B_del = new JButton("删除");
		
		B_del.setBounds(196, 169, 83, 23);
		P_student_info.add(B_del);
		
		TF_name = new JTextField();
		TF_name.setEditable(false);
		TF_name.setColumns(10);
		TF_name.setBounds(125, 21, 113, 21);
		P_student_info.add(TF_name);
		
		L_name = new JLabel("姓名");
		L_name.setHorizontalAlignment(SwingConstants.RIGHT);
		L_name.setBounds(61, 24, 54, 15);
		P_student_info.add(L_name);
		
		L_sex = new JLabel("性别");
		L_sex.setHorizontalAlignment(SwingConstants.RIGHT);
		L_sex.setBounds(61, 49, 54, 15);
		P_student_info.add(L_sex);
		
		student_sex_boy = new JRadioButton("男");
		student_sex_boy.setEnabled(false);
		buttonGroup.add(student_sex_boy);
		student_sex_boy.setSelected(true);
		student_sex_boy.setBounds(125, 45, 54, 23);
		P_student_info.add(student_sex_boy);
		
		student_sex_girl = new JRadioButton("女");
		student_sex_girl.setEnabled(false);
		buttonGroup.add(student_sex_girl);
		student_sex_girl.setBounds(181, 45, 54, 23);
		P_student_info.add(student_sex_girl);
		
		TF_number = new JTextField();
		TF_number.setEditable(false);
		TF_number.setColumns(10);
		TF_number.setBounds(312, 21, 116, 21);
		P_student_info.add(TF_number);
		
		L_number = new JLabel("学号");
		L_number.setHorizontalAlignment(SwingConstants.RIGHT);
		L_number.setBounds(248, 24, 54, 15);
		P_student_info.add(L_number);
		
		L_room = new JLabel("宿舍");
		L_room.setHorizontalAlignment(SwingConstants.RIGHT);
		L_room.setBounds(248, 49, 54, 15);
		P_student_info.add(L_room);
		
		
		
		CB_room = new JComboBox<String>();
		CB_room.setModel(new DefaultComboBoxModel<String>());
		CB_room.removeAllItems();
		
		
		
		
		CB_room.setBounds(312, 46, 116, 21);
		P_student_info.add(CB_room);
		
		TF_note = new JTextField();
		TF_note.setEditable(false);
		TF_note.setColumns(10);
		TF_note.setBounds(125, 71, 303, 21);
		P_student_info.add(TF_note);
		
		L_note = new JLabel("备注");
		L_note.setHorizontalAlignment(SwingConstants.RIGHT);
		L_note.setBounds(61, 74, 54, 15);
		P_student_info.add(L_note);
		B_enter = new JButton("确认");
		B_enter.setBounds(289, 169, 83, 23);
		P_student_info.add(B_enter);
		
		B_cancel = new JButton("取消");
		B_cancel.setBounds(382, 169, 83, 23);
		P_student_info.add(B_cancel);
		
		L_roommate = new JLabel("室友");
		L_roommate.setHorizontalAlignment(SwingConstants.RIGHT);
		L_roommate.setBounds(61, 99, 54, 15);
		P_student_info.add(L_roommate);
		
		scrollPane_1 = new JScrollPane();
		scrollPane_1.setEnabled(false);
		scrollPane_1.setBounds(125, 96, 303, 63);
		scrollPane_1.setBorder(null);
		P_student_info.add(scrollPane_1);
		
		TP_roommate = new JTextPane();
		TP_roommate.setEditable(false);
		TP_roommate.setForeground(new Color(0, 0, 0));
		scrollPane_1.setViewportView(TP_roommate);
		TP_roommate.setBackground(new Color(240, 240, 240));
		
		TF_search = new JTextField();
		TF_search.setBounds(111, 21, 297, 21);
		add(TF_search);
		TF_search.setColumns(10);
		
		comboBox = new JComboBox<String>();
		comboBox.setModel(new DefaultComboBoxModel<String>(new String[] {"全部", "男", "女"}));
		comboBox.setSelectedIndex(0);
		comboBox.setBounds(10, 21, 91, 21);
		add(comboBox);
		
		B_search = new JButton("搜索");
		
		B_search.setBounds(418, 20, 113, 23);
		add(B_search);
		L_roommate.setVisible(false);
		B_add.setEnabled(true);
		B_fix.setEnabled(false);
		B_del.setEnabled(false);
		B_enter.setEnabled(false);
		B_cancel.setEnabled(false);
		
		table.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				B_add.setEnabled(false);
				B_fix.setEnabled(true);
				B_del.setEnabled(true);
				B_enter.setEnabled(false);
				B_cancel.setEnabled(true);
				int w = table.getSelectedRow();
				TF_number.setText(all_data.get(w)[0].toString());
				TF_number.setEditable(false);
				TF_name.setEditable(false);
				student_sex_boy.setEnabled(false);
				student_sex_girl.setEnabled(false);
				scrollPane_1.setVisible(true);
				TF_note.setEditable(false);
				TF_name.setText(all_data.get(w)[1].toString());
				if(all_data.get(w)[2].toString().equals("boy")){
					student_sex_boy.setSelected(true);
					student_sex_girl.setSelected(false);
				}else{
					student_sex_boy.setSelected(false);
					student_sex_girl.setSelected(true);
				}
				
				TF_note.setText(all_data.get(w)[4].toString());
				TP_roommate.setBorder(TF_note.getBorder());
				TP_roommate.setText(getRoommate(all_data.get(w)[0].toString(),all_data.get(w)[3].toString()));
				TP_roommate.setVisible(true);
				L_roommate.setVisible(true);
				
				CB_room.removeAllItems();
				CB_room.addItem(all_data.get(w)[3].toString());
			}
		});

		B_add.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				
				B_add.setEnabled(false);
				B_fix.setEnabled(false);
				B_del.setEnabled(false);
				B_enter.setEnabled(true);
				B_cancel.setEnabled(true);
				TF_number.setEditable(true);
				TF_name.setEditable(true);
				
				TF_note.setEditable(true);
				student_sex_boy.setEnabled(true);
				student_sex_girl.setEnabled(true);
				TP_roommate.setVisible(false);
				L_roommate.setVisible(false);
				CB_room.setEnabled(true);
				updateComboBox();
				S_lastPerform = "add";
				scrollPane_1.setEnabled(false);
				scrollPane_1.setVisible(false);
			}
		});
		
		B_fix.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				
				B_add.setEnabled(false);
				B_fix.setEnabled(false);
				B_del.setEnabled(false);
				B_enter.setEnabled(true);
				B_cancel.setEnabled(true);
				TF_number.setEditable(true);
				TF_name.setEditable(true);
				
				TF_note.setEditable(true);
				student_sex_boy.setEnabled(true);
				student_sex_girl.setEnabled(true);
				TP_roommate.setVisible(false);
				L_roommate.setVisible(false);
				CB_room.setEnabled(true);
				updateComboBox();
				S_lastPerform = "fix";
				scrollPane_1.setEnabled(false);
				scrollPane_1.setVisible(false);
			}
		});
		
		B_del.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				
				String sendMsg = "{\"method\":\"delete_student\",\"student_number\":\""+TF_number.getText()+"\"}";
				try{
					JSONObject obj = new JSONObject(new SocketOp().request(sendMsg));
					if(obj.has("result")&&obj.getString("result").equals("success")){
						JOptionPane.showMessageDialog(null, "成功删除一个数据", "删除数据", JOptionPane.INFORMATION_MESSAGE);
					}else{
						JOptionPane.showMessageDialog(null, "删除失败", "删除数据", JOptionPane.ERROR_MESSAGE);
					}
				}catch(Exception e1){
					JOptionPane.showMessageDialog(null, "删除失败", "删除数据", JOptionPane.ERROR_MESSAGE);
				}
				table.clearSelection();
				scrollPane_1.setEnabled(false);
				scrollPane_1.setVisible(false);
				B_add.setEnabled(true);
				B_fix.setEnabled(false);
				B_del.setEnabled(false);
				B_enter.setEnabled(false);
				B_cancel.setEnabled(false);
				TP_roommate.setVisible(false);
				L_roommate.setVisible(false);
				TF_number.setText("");
				TF_name.setText("");
				TF_note.setText("");
				student_sex_boy.setSelected(true);
				student_sex_girl.setSelected(false);
				TP_roommate.setVisible(false);
				L_roommate.setVisible(false);
				TP_roommate.setBorder(null);
				CB_room.setEnabled(false);
				
				if(comboBox.getSelectedIndex()==0)	sendMsg= "{\"method\":\"show_student\",\"student_sex\":\"all\"}";
				else if(comboBox.getSelectedIndex()==1)	sendMsg= "{\"method\":\"show_student\",\"student_sex\":\"boy\"}";
				else if(comboBox.getSelectedIndex()==2)	sendMsg= "{\"method\":\"show_student\",\"student_sex\":\"girl\"}";
				updateData(sendMsg);
				S_lastPerform = "del";
			}
		});
		
		B_enter.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if(TF_name.getText().equals("")){
					JOptionPane.showMessageDialog(null, "姓名不得为空", "姓名错误", JOptionPane.ERROR_MESSAGE);
					return;
				}
				if(checkTextLengh(TF_name.getText(),20,"姓名") ){
						if(S_lastPerform.equals("add")&&checkID(TF_number.getText())){
							JOptionPane.showMessageDialog(null, "add");
						}else if(S_lastPerform.equals("fix")&&(TF_number.getText().equals(all_data.get(table.getSelectedRow())[0].toString())||checkID(TF_number.getText()))){
							JOptionPane.showMessageDialog(null, "fix");
						}else{
							return;
						}
					
				}else{
					return;
				}
				if(!checkTextLengh(TF_note.getText(),200,"备注") ){
					return;
				}//备注不得长于200
				B_add.setEnabled(true);
				B_fix.setEnabled(false);
				B_del.setEnabled(false);
				B_enter.setEnabled(false);
				B_cancel.setEnabled(false);
				TF_number.setEditable(false);
				TF_name.setEditable(false);
				scrollPane_1.setEnabled(false);
				scrollPane_1.setVisible(false);
				TF_note.setEditable(false);
				student_sex_boy.setEnabled(false);
				student_sex_girl.setEnabled(false);
				CB_room.setEnabled(false);
				String sendMsg = "{\"method\":\"import_student\",\"student_name\":\""+TF_name.getText()+"\",\"student_number\":\""+TF_number.getText()+"\",\"student_sex\":\""+(student_sex_boy.isSelected()?"boy":"girl")+"\",\"student_room\":\""+CB_room.getSelectedItem()+"\",\"student_note\":\""+TF_note.getText()+"\"}";
				
				if(S_lastPerform.equals("add")){
					try{
						JSONObject obj = new JSONObject(new SocketOp().request(sendMsg));
						if(obj.has("result")&&obj.getString("result").equals("success")){
							JOptionPane.showMessageDialog(null, "添加成功", "添加数据", JOptionPane.INFORMATION_MESSAGE);
						}else{
							throw new Exception();
						}
					}catch(Exception e1){
						JOptionPane.showMessageDialog(null, "添加失败", "添加数据", JOptionPane.ERROR_MESSAGE);
					}
				}else if(S_lastPerform.equals("fix")){
					try{
						String sendMsg1 = "{\"method\":\"delete_student\",\"student_number\":\""+all_data.get(table.getSelectedRow())[0].toString()+"\"}";
						JSONObject obj = new JSONObject(new SocketOp().request(sendMsg1));
						if(obj.has("result")&&obj.getString("result").equals("success")){
							obj = new JSONObject(new SocketOp().request(sendMsg));
							if(obj.has("result")&&obj.getString("result").equals("success")){
								JOptionPane.showMessageDialog(null, "修改成功", "修改数据", JOptionPane.INFORMATION_MESSAGE);
							}else{
								throw new Exception();
							}
						}else{
							throw new Exception();
						}
					}catch(Exception e1){
						JOptionPane.showMessageDialog(null, "修改成功", "修改数据", JOptionPane.INFORMATION_MESSAGE);
					}
				}
				S_lastPerform = "enter";
				clearData();
				if(comboBox.getSelectedIndex()==0)	sendMsg= "{\"method\":\"show_student\",\"student_sex\":\"all\"}";
				else if(comboBox.getSelectedIndex()==1)	sendMsg= "{\"method\":\"show_student\",\"student_sex\":\"boy\"}";
				else sendMsg= "{\"method\":\"show_student\",\"student_sex\":\"girl\"}";
				updateData(sendMsg);
				
			}
		});
		
		B_cancel.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				S_lastPerform = "cancel";
				B_add.setEnabled(true);
				B_fix.setEnabled(false);
				B_del.setEnabled(false);
				B_enter.setEnabled(false);
				B_cancel.setEnabled(false);
				scrollPane_1.setEnabled(false);
				scrollPane_1.setVisible(false);
				TF_number.setText("");
				TF_name.setText("");
				TF_note.setText("");
				student_sex_boy.setSelected(true);
				student_sex_girl.setSelected(false);
				TF_number.setEditable(false);
				TF_name.setEditable(false);
				TF_note.setEditable(false);
				student_sex_boy.setEnabled(false);
				student_sex_girl.setEnabled(false);
				TP_roommate.setVisible(false);
				L_roommate.setVisible(false);
				CB_room.setEnabled(false);
				TP_roommate.setBorder(null);
			}
		});
		
		B_search.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				String sendMsg = null;
				if(comboBox.getSelectedIndex()==0)	
					sendMsg= "{\"method\":\"search_student\",\"student_sex\":\"all\",\"student_info\":\""+TF_search.getText()+"\"}";
				else if(comboBox.getSelectedIndex()==1)	
					sendMsg= "{\"method\":\"search_student\",\"student_sex\":\"boy\",\"student_info\":\""+TF_search.getText()+"\"}";
				else if(comboBox.getSelectedIndex()==2)	
					sendMsg= "{\"method\":\"search_student\",\"student_sex\":\"girl\",\"student_info\":\""+TF_search.getText()+"\"}";
				updateData(sendMsg);
				
			}
		});
		
		comboBox.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				String sendMsg = null;
				if(comboBox.getSelectedIndex()==0)	sendMsg= "{\"method\":\"show_student\",\"student_sex\":\"all\"}";
				else if(comboBox.getSelectedIndex()==1)	sendMsg= "{\"method\":\"show_student\",\"student_sex\":\"boy\"}";
				else if(comboBox.getSelectedIndex()==2)	sendMsg= "{\"method\":\"show_student\",\"student_sex\":\"girl\"}";
				updateData(sendMsg);
			}
		});
		
		
		student_sex_girl.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				updateComboBox();
			}
		});
		student_sex_boy.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				updateComboBox();
			}
		});
	}
}
